package com.example.project.projectspringcloud.controller.admin.order;

import com.example.project.projectspringcloud.common.Constants;
import com.example.project.projectspringcloud.common.OperationException;
import com.example.project.projectspringcloud.controller.BaseController;
import com.example.project.projectspringcloud.entity.Page;
import com.example.project.projectspringcloud.entity.RespBody;
import com.example.project.projectspringcloud.entity.discountcoupon.DiscountCoupon;
import com.example.project.projectspringcloud.entity.order.Order;
import com.example.project.projectspringcloud.entity.user.User;
import com.example.project.projectspringcloud.service.discountcoupon.DiscountCouponService;
import com.example.project.projectspringcloud.service.order.OrderDetailService;
import com.example.project.projectspringcloud.service.order.OrderService;
import com.example.project.projectspringcloud.service.user.UserService;
import com.example.project.projectspringcloud.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

@Api(tags = "后台订单管理")
@Controller
@RequestMapping(value = "/admin/order")
public class AdminOrderController extends BaseController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private DiscountCouponService discountCouponService;

    @Autowired
    private UserService userService;

    @ApiOperation(value = "订单管理列表", notes = "返回订单管理列表")
    @RequestMapping(value = {"", "/list"})
    public String list(Order order, Page page, Model model) {
        List<Order> orders = orderService.list(page, order);
        model.addAttribute("page", new Page<Order>(orders));
        model.addAttribute("order", order);
        return "admin/order/order-list";
    }

    @ApiOperation(value = "获取订单表单", notes = "返回订单表单")
    @GetMapping(value = "/form/{orderId}")
    public String form(@PathVariable("orderId") Integer orderId, Model model) {
        Order order = orderService.get(new Order(orderId));
        if (order.getDiscount() != null) {
            order.setDiscountCoupon(discountCouponService.get(new DiscountCoupon(order.getDiscount())));
        }
        model.addAttribute("order", order);

        User entity = new User();
        entity.setType(4);
        model.addAttribute("photoGrapher", userService.list(null, entity));

        entity.setType(5);
        model.addAttribute("scriptWriter", userService.list(null, entity));

        return "admin/order/order-form";
    }

    @ApiOperation(value = "保存订单", notes = "管理员保存订单")
    @PostMapping(value = "/api/save")
    @ResponseBody
    public RespBody save(Order order) throws OperationException {
        boolean result = orderService.save(order);
        return RespBody.ok(result);
    }

    @ApiOperation(value = "删除订单", notes = "管理员删除订单")
    @DeleteMapping(value = "/api/delete/{ids}")
    @ResponseBody
    public RespBody delete(@PathVariable("ids") String ids) {
        if (StringUtils.isBlank(ids)) {
            return RespBody.error(Constants.Message.PARAM_INVALID);
        }
        if (!orderService.delete(StringUtil.split(ids, Constants.Punctuation.COMMA))) {
            return RespBody.error(Constants.Message.DELETE_FAILED);
        }
        return RespBody.ok(Constants.Message.DELETE_SUCCESS);
    }

    @ApiOperation(value = "API调整订单价格", notes = "调整订单价格")
    @PostMapping(value = "/api/update-price")
    @ResponseBody
    public RespBody price(@RequestParam(value = "id") Integer id,
                          @RequestParam(value = "changePrice") BigDecimal changePrice) throws OperationException {
        Order order = orderService.get(new Order(id));
        if (Optional.ofNullable(order).isPresent()) {
            order.setTotalPrice(changePrice);

            // 如果订单类型为私人订制, 或者作品类型为宣传片, 并且订单状态为待支付-未评估, 则调整价格后, 设置二级状态为已评估
            if ((order.getType().equals(2) || order.getOrderDetail().getVideoType().equals(4)) && order.getStatus().equals(2)) {
                order.setStatusStep(0);
            }
            orderService.save(order);
        } else {
            return RespBody.error(super.translateI18N(Constants.Message.ORDER_DOES_NOT_EXIST));
        }
        return RespBody.ok(true);
    }

    @ApiOperation(value = "API分配摄影师、编剧", notes = "分配摄影师、编剧")
    @PostMapping(value = "/api/distribution")
    @ResponseBody
    public RespBody distribution(@RequestParam("orderId") Integer orderId,
                                 @RequestParam("photoGrapher") Integer photoGrapher,
                                 @RequestParam("scriptWriter") Integer scriptWriter) throws OperationException {
        Order order = orderService.get(new Order(orderId));
        if (Optional.ofNullable(order).isPresent()) {
            order.getOrderDetail().setPhotographer(photoGrapher);
            order.getOrderDetail().setScriptwriter(scriptWriter);

            orderDetailService.save(order.getOrderDetail());
        } else {
            return RespBody.error(super.translateI18N(Constants.Message.ORDER_DOES_NOT_EXIST));
        }
        return RespBody.ok(true);
    }

    @ApiOperation(value = "API上传套餐", notes = "更新私人定制套餐")
    @PostMapping(value = "/api/update-combo")
    @ResponseBody
    public RespBody updateCombo(@RequestParam("orderId") Integer orderId,
                                @RequestParam("comboFile") String comboFile) {
        try {
            Order order = orderService.get(new Order(orderId));
            if (Optional.ofNullable(order).isPresent()) {
                // 如果是私人订制
                if (order.getType().equals(2)) {
                    order.getOrderDetail().setComboFile(comboFile);
                }

                orderDetailService.save(order.getOrderDetail());
                return RespBody.ok(true);
            } else {
                return RespBody.error(super.translateI18N(Constants.Message.ORDER_DOES_NOT_EXIST));
            }
        } catch (Exception e) {
            return RespBody.error(super.translateI18N(Constants.SystemMessage.SYSTEM_ERROR));
        }
    }

}
